using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Aurora.Discovery.HttpClient.Abstractions;

/// <summary>
/// discovery 扩展类
/// </summary>
public static class DiscoveryExtension
{
    public static void AddDiscovery(this IServiceCollection services, Action<DiscoveryOptions> setupAction)
    {
        if (setupAction == null) throw new ArgumentNullException(nameof(setupAction));

        // services.Configure<ConsulDiscoveryOptions>(configuration.GetSection("DiscoveryClient"));
        // services.AddSingleton<DiscoveryClient>();
        services.AddScoped<DiscoveryHttpMessageHandler>();

        DiscoveryOptions options = new DiscoveryOptions();
        setupAction(options);
        foreach (var discoveryOptionsExtension in options.Extensions)
        {
            discoveryOptionsExtension.AddServices(services);
        }
    }

    public static IHttpClientBuilder AddHttpClientDiscovery(this IHttpClientBuilder builder)
    {
        builder.AddHttpMessageHandler<DiscoveryHttpMessageHandler>();
        return builder;
    }


    /// <summary>
    /// 使用服务发现与注册
    /// </summary>
    /// <param name="app"></param>
    /// <returns></returns>
    public static IApplicationBuilder UseDiscovery(this IApplicationBuilder app)
    {
        var lifetime = app.ApplicationServices.GetService<IHostApplicationLifetime>();
        var discoveryClient = app.ApplicationServices.GetService<IDiscoveryClient>();
        discoveryClient.Use(app);
        lifetime?.ApplicationStarted.Register(() => { discoveryClient?.Start(); });

        lifetime?.ApplicationStopping.Register(() => { discoveryClient?.Stop(); });
        return app;
    }
}